/**
 * // Definition for a Node.
 * function Node(val, next, random) {
 *    this.val = val;
 *    this.next = next;
 *    this.random = random;
 * };
 */

/**
 * @param {Node} head
 * @return {Node}
 */
 var copyRandomList = function(head) {
    if(!head) return null;
    let newhead = null;
    let arr = [];
    let newarr;
    let node = head;
    while(node){
        arr.push(node);
        node = node.next;
    }
    
    newarr = new Array(arr.length).fill(null)
    newhead = new Node(head.val);
    node = newhead;

    

    for(let i=0;i<arr.length;i++){
        let newNode=newarr[i];
        if(!newarr[i]){
            newNode=new Node(arr[i].val);
            newarr[i] = newNode; 
        }
        node.next = newNode;
        node = node.next;
        let index = arr.indexOf(arr[i].random);
        if(index === -1){
            node.random = null
        }
        else{
            if(!newarr[index]){
                let newNode = new Node(arr[index].val);
                newarr[index] = newNode;
                node.random = newNode;
            }
            else{
                node.random = newarr[index];
            }
        }
    }
    return newhead.next;
};